package com.wangzifan.controller;

import com.wangzifan.entity.Result;
import com.wangzifan.entity.User;
import com.wangzifan.properties.JwtProperties;
import com.wangzifan.service.UserService;
import com.wangzifan.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;


@RestController
@Slf4j
public class LoginController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        log.info("用户登录：{}", user);
        User u = userService.queryUserByAccount(user);

        if (u != null) {
            Map<String, Object> Claims = new HashMap<>();
            Claims.put("id", u.getId());
            Claims.put("name", u.getUsername());
            String jwt = JwtUtil.createJWT(jwtProperties.getAdminSecretKey(), jwtProperties.getAdminTtl(), Claims);
            return Result.success(jwt);
        }
        return Result.error("用户名或密码错误！");
    }
}
